<template>
  <div class="foodItem-container">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <template #success>
        <i class="iconfont icon-success"></i>
        加载成功
      </template>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div class="food-wrap">
          <div
            class="food"
            v-for="food in foodList"
            :key="food.id"
            @click="toDetail(food.id)"
          >
            <div class="food-face">
              <van-image round :src="food.face" fit="cover" />
            </div>
            <div class="food-name">
              <span>{{ food.name }}</span>
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getFoodByAffectCate } from "@/api/food";
export default {
  name: "FoodItem",

  props: {
    affectCate: {
      type: Object,
    },
  },

  data() {
    return {
      foodList: [],
      page: 1,
      loading: false,
      finished: false,
      refreshing: false,
    };
  },

  mounted() {},

  methods: {
    toDetail(foodId) {
      this.$router.push({
        name: "foodDetail",
        params: {
          foodId,
        },
      });
    },

    onLoad() {
      if (this.refreshing) {
        this.page = 1;
        this.foodList = [];
        this.refreshing = false;
      }

      let params = {
        page: this.page,
        affectCate: this.affectCate.id,
      };

      getFoodByAffectCate(params).then((res) => {
        if (res.data.length > 0) {
          this.foodList = [...this.foodList, ...res.data];
        } else if (res.data.length == 0) {
          this.finished = true;
        }
        this.page++;
        this.loading = false;
      });
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      setTimeout(() => {
        this.onLoad();
      }, 1000);
    },
  },
};
</script>

<style lang="less" scoped>
.foodItem-container {
  width: 100%;
  height: auto;

  .food-wrap {
    width: 335px;
    height: auto;
    margin: 0 auto;
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;

    .food {
      width: 167px;
      height: 164px;
      box-sizing: border-box;
      padding: 10px 25px 10px 25px;

      .food-face {
        width: 117px;
        height: 117px;

        .van-image {
          width: 117px;
          height: 117px;
        }
      }

      .food-name {
        width: 117px;
        height: auto;

        span {
          display: inline-block;
          width: 100%;
          text-align: center;
          font-size: 15px;
        }
      }
    }
  }
}
</style>